package semantic.rules.walk

import utils.data.CTree
import scala.collection.mutable.Buffer
import syntax.CASTNode
import lexis.CLexemeType
import semantic.COperations._
import semantic.CLabels._
import syntax.CGrammar._
import semantic.CDataTypes._

object CWalkRuleIfElse extends CWalkRule
{
    override val categories = CIfElse :: Nil

    override def post(node:CASTNode)(implicit tree:CTree[CASTNode], code:Buffer[String]) =
        if (code.isEmpty) code += s"$LABEL_IF_ELSE_END${node id}"
        else code(code.size - 1) += s"$LABEL_IF_ELSE_END${node id}"

    override def postChild(node:CASTNode, child:CASTNode)(implicit tree:CTree[CASTNode], code:Buffer[String]) =
        if (node.category == CIfElse && (node().nChild(4).is(c => c == child && c.category == CFlow) || node().nChild(3).is(c => c == child && c.category == CFlowUnit)))
        {
            code += s"$PUSH $LABEL_IF_GOTO${node id}" += GO_TO
            if (!node().isChildExist(_.category == CLexemeType.ELSE)) code += s"$PUSH $NULL"
        }
        else if (node.category == CIfElse && node().secondChild.is(_ == child)) code += s"$PUSH $LABEL_IF_ELSE_TARGET${node id}" += IF
}
